package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService implements com.sky.service.UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    //微信服务接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User UserLogin(UserLoginDTO userLoginDTO) {
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");




       String josn =  HttpClientUtil.doGet(WX_LOGIN,map);
        JSONObject jsonObject = JSON.parseObject(josn);
        String openid = jsonObject.getString("openid");
        //如果openid不存在，就抛出异常
        if(openid == null){
             throw new RuntimeException(MessageConstant.LOGIN_FAILED);
        }
        //查看用户是否为新用户
        User user = userMapper.GetByopenid(openid);
        //如果不是，则创建新用户并登录
        if(user == null){
      user =  User.builder()
                .openid(openid)
                .createTime(LocalDateTime.now())
                .build();
      userMapper.insert(user);}


        return user;
    }
}
